package com.spark.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spark.common.constants.validGroup.AddGroup;
import com.spark.common.constants.validGroup.EditGroup;
import com.spark.common.core.Result;
import com.spark.common.core.api.SparkCommonApi;
import com.spark.common.query.QueryGenerator;
import com.spark.common.core.entity.system.SysParams;
import com.spark.modules.system.service.ISysParamsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 系统参数配置Controller
 *
 * @author LYCHEE
 * @date 2025/03/22 11:13
 */
@RestController
@RequestMapping(value = "/system/sysParams")
public class SysParamsController {

    @Resource
    private ISysParamsService sysParamsService;
    @Resource
    private SparkCommonApi sparkCommonApi;

    /**
     * 分页列表查询
     *
     * @param sysParams 系统参数配置对象
     * @param pageNo   分页
     * @param pageSize 分页
     * @return 系统参数配置列表
     */
    @PreAuthorize("@sp.hasPerm('sys:params:query')")
    @GetMapping(value = "/queryPageList")
    public Result<?> queryPageList(SysParams sysParams,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SysParams> queryWrapper = QueryGenerator.initQueryWrapper(sysParams);
        Page<SysParams> page = new Page<SysParams>(pageNo, pageSize);
        IPage<SysParams> pageList = sysParamsService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 列表查询
     *
     * @param sysParams 系统参数配置对象
     * @return 系统参数配置列表
     */
    @PreAuthorize("@sp.hasPerm('sys:params:query')")
    @GetMapping(value = "/queryList")
    public Result<?> queryList(SysParams sysParams) {
        QueryWrapper<SysParams> queryWrapper = QueryGenerator.initQueryWrapper(sysParams);
        List<SysParams> list = sysParamsService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统参数配置对象
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam String id) {
        SysParams sysParams = sysParamsService.getById(id);
        if (Objects.isNull(sysParams)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(sysParams);
    }

    /**
     * 新增
     *
     * @param sysParams 系统参数配置对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:paramsItem:add')")
    @PostMapping(value = "/add")
    public Result<?> add(@Validated(AddGroup.class) @RequestBody SysParams sysParams) {
        boolean save = sysParamsService.save(sysParams);
        if (save) {
            sparkCommonApi.refreshParamsCache(true);
        }
        return Result.flag(save);
    }

    /**
     * 编辑
     *
     * @param sysParams 系统参数配置对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:paramsItem:edit')")
    @PostMapping(value = "/edit")
    public Result<?> edit(@Validated(EditGroup.class) @RequestBody SysParams sysParams) {
        boolean update = sysParamsService.updateById(sysParams);
        if (update) {
            sparkCommonApi.refreshParamsCache(true);
        }
        return Result.flag(update);
    }

    /**
     * 通过id删除
     *
     * @param id 主键
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:paramsItem:del')")
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") String id) {
        boolean update = sysParamsService.removeById(id);
        if (update) {
            sparkCommonApi.refreshParamsCache(true);
        }
        return Result.flag(update);
    }

    /**
     * 通过id批量删除删除
     *
     * @param ids 主键
     * @return 成功或失败
     */
    @DeleteMapping(value = "/deleteBatchByIds/{ids}")
    public Result<?> deleteBatchByIds(@PathVariable(name = "ids") String[] ids) {
        boolean update = sysParamsService.removeBatchByIds(Arrays.asList(ids));
        if (update) {
            sparkCommonApi.refreshParamsCache(true);
        }
        return Result.flag(update);
    }

    /**
     * 编辑值
     *
     * @param params 参数
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:paramsItem:submit')")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping(value = "/editVal")
    public Result<?> editVal(@RequestBody Map<String, String> params) {
        for (String key : params.keySet()) {
            String val = params.get(key);
            if (StringUtils.isEmpty(val)) {
                val = "";
            }
            LambdaUpdateWrapper<SysParams> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysParams::getConfigField, key);
            sysParamsService.update(new SysParams().setInputVal(val), updateWrapper);
        }
        sparkCommonApi.refreshParamsCache(true);
        return Result.ok("配置已保存");
    }

}
